import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as ContactQueryAction from '../actions/contacterQuery'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

 import WeaFormmodeTop from './WeaFormmodeTop'

import { WeaTable } from 'comsRedux'

const WeaTableAction = WeaTable.action;

import {
    WeaTab,
    WeaLeftTree,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm,
    WeaTop
} from 'ecCom'

import {WeaErrorPage,WeaTools,WeaAlertPage} from 'ecCom'
const { getComponent } = WeaTools;

import {Button,Form,Modal,message,Spin} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class ContactQuery extends React.Component {
    constructor(props) {
		super(props);
		_this = this;
    }
    componentDidMount() {
    	 const {actions} = this.props;
         actions.setNowRouterCmpath('contactQuery');
         actions.initDatas();
         actions.doSearch();
    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        if(keyOld!==keyNew) {
            const {actions,isClearNowPageStatus} = this.props;
            actions.unmountClear(isClearNowPageStatus);
            actions.isClearNowPageStatus(false);

            actions.setNowRouterCmpath('contactQuery');
            actions.doSearch();
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.dataKey,nextProps.dataKey)||
        !is(this.props.conditioninfo,nextProps.conditioninfo)||
        !is(this.props.showSearchAd,nextProps.showSearchAd)||
        !is(this.props.searchParamsAd,nextProps.searchParamsAd)||
        !is(this.props.loading,nextProps.loading)||
        !is(this.props.comsWeaTable,nextProps.comsWeaTable)||
        !is(this.props.orderFields,nextProps.orderFields)||
        !is(this.props.isClearNowPageStatus,nextProps.isClearNowPageStatus)||
        !is(this.props.hasright,nextProps.hasright);
    }
    componentWillUnmount(){
    	const {actions,isClearNowPageStatus} = this.props;
        actions.unmountClear(isClearNowPageStatus);
         actions.isClearNowPageStatus(false);
    }
    render() {
        let that = this;
        const {loading,comsWeaTable,actions,title,dataKey,showSearchAd,searchParamsAd,hasright} = this.props;
        const name = dataKey ? dataKey.split('_')[0] : 'init';
        const loadingTable = comsWeaTable.get(name).toJS().loading;
        const selectedRowKeys = comsWeaTable.get('selectedRowKeys');
        if(hasright == "-1"){
            return (
				<div className="align-center top40">
					<Spin size="large"></Spin>
				</div>);
        }else if(!hasright){
            return (
                <WeaTop  
                    title={title}
                    loading={true}
                    icon={<i className='icon-coms-crm' />}
                    iconBgcolor='#96358a'
                    buttons={[]}
                    buttonSpace={10}
                    showDropIcon={false}
                    dropMenuDatas={[]}
                >
                <WeaAlertPage>
                    <div className="color-black">
                        对不起，您暂时没有权限
                    </div>
                </WeaAlertPage>
            </WeaTop>);
        }else{
            return (
                <div className="crm-top-req">
                    <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                        <WeaFormmodeTop 
                            title={title}
                            loading={loading || loadingTable}
                            icon={<i className='icon-coms-crm' />}
                            iconBgcolor='#96358a'
                            buttons={[]}
                            buttonSpace={10}
                            showDropIcon={true}  
                            dropMenuDatas={this.getRightMenu()}
                            onDropMenuClick={this.onRightMenuClick.bind(this)}

                            buttonsAd={this.getTabButtonsAd()}  //高级搜索底部button
                            searchType={['base','advanced']}
                            searchsBaseValue={searchParamsAd.get('firstname')}  //外部inpt默认初始值
                            setShowSearchAd={bool=>{actions.setShowSearchAd(bool)}}
                            hideSearchAd={()=> actions.setShowSearchAd(false)}
                            searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                            showSearchAd={showSearchAd}
                            onSearch={v=>{actions.doSearch()}}
                            onSearchChange={v=>{actions.saveOrderFields({firstname:{name:'firstname',value:v}})}}
                        >
                            <WeaTable 
                                sessionkey={dataKey}
                                hasOrder={true}
                                needScroll={true}
                                onOperatesClick={this.onOperatesClick.bind(this)}
                            />
                        </WeaFormmodeTop>
                    </WeaRightMenu>
                </div>
            )
        }
    }
    onRightMenuClick(key){
    	 const {actions,comsWeaTable,dataKey} = this.props;
    	if(key == '0'){
    		actions.doSearch();
    		actions.setShowSearchAd(false)
    	}
    	if(key == '1'){
            actions.setColSetVisible(dataKey,true);
    		actions.tableColSet(dataKey,true)
    	}
    	if(key == '2'){
    		// actions.setColSetVisible(dataKey,true);
    		// actions.tableColSet(true)
        }
        if(key == '4'){
    		// actions.setColSetVisible(dataKey,true);
    		// actions.tableColSet(true)
    	}
    }
    getRightMenu(){
    	let btns = [];
    	btns.push({
    		icon: <i className='icon-coms-search'/>,
            content:'搜索',
            key:0
    	});
        btns.push({
    		icon: <i className='icon-coms-Custom'/>,
            content:'显示定制列',
            key:1
    	});
        btns.push({
            icon: <i className='icon-coms-Collection'/>,
            content:'收藏',
            key:2
        });
    	btns.push({
            icon: <i className='icon-coms-help'/>,
            content:'帮助',
            key:3
        });
    	return btns
    }
    getSearchs() {
        const {conditioninfo} = this.props;
         let conditionAttr = [];
         conditioninfo.map((item,index)=>{
            conditionAttr.push(
                <WeaSearchGroup needTigger={true} title={this.getTitle(index)} showGroup={this.isShowFields(index)} items={this.getFields(index)}/>
            );
         });
         return conditionAttr;
    }
    getTitle(index = 0) {
       const {conditioninfo} = this.props;
       return !isEmpty(conditioninfo.toJS()) && conditioninfo.toJS()[index].title
    }
    isShowFields(index = 0) {
        const {conditioninfo} = this.props;
        return !isEmpty(conditioninfo.toJS()) && conditioninfo.toJS()[index].defaultshow
    }
    // 0 常用条件，1 其他条件
    getFields(index = 0) {
       const {conditioninfo} = this.props;
       
        const fieldsData = !isEmpty(conditioninfo.toJS()) && conditioninfo.toJS()[index].items;
        let items = [];
        forEach(fieldsData, (field) => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                        {WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                    </FormItem>),
                colSpan:1
            })
        });
        return items;
    }

    changeData(theKey) {
        const {actions} = this.props;
        actions.setShowSearchAd(false);
        actions.doSearch({
            viewcondition:theKey //keyArr.length>1?keyArr[1]:""
        },{});
    }
   
    getTabButtonsAd() {
    	const {actions} = this.props;
        return [
            (<Button type="primary" onClick={()=>{actions.doSearch();actions.setShowSearchAd(false)}}>搜索</Button>),
            (<Button type="ghost" onClick={()=>{actions.saveOrderFields({})}}>重置</Button>),
            (<Button type="ghost" onClick={()=>{actions.setShowSearchAd(false)}}>取消</Button>)
        ]
    }
    onOperatesClick(record,index,operate,flag){
        // console.log(record,index,operate,flag);
       const {actions} = this.props;
        if(flag=="3"){  //查看
            crmOpenSelf('/main/crm/contacterView?contacterId='+record.randomFieldId);
        }
    }

}


let Sys = {};
let ua = navigator.userAgent.toLowerCase();
let s;
(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;


window.crmOpenSPA4SingleTab = function(routeUrl,id) {
    window.crmOpenSPA4Single(routeUrl,id,true);
}
window.crmOpenSelf = function(routeUrl,id,opentab){
    window.open("/spa/crm/index.html#"+routeUrl, "_blank");
}

window.crmOpenSPA4Single = function(routeUrl,id,opentab) {
    let obj = jQuery("#hiddenPreLoaderSinglecrm").length>0 ? jQuery("#hiddenPreLoaderSinglecrm"):jQuery("#hiddenPreLoaderSingle");

    let spaWin = null;
    if(Sys.chrome) {
        $(window).mousedown(function(){});
        obj.attr("src","");
        obj.attr("src","/spa/crm/index.html");
    }

    const _timekey = new Date().getTime();
   // routeUrl += "&preloadkey=" + _timekey;

    const width = screen.availWidth - 10;
	const height = screen.availHeight - 50;
    let szFeatures = "";
    if(!opentab){
	szFeatures = "top=0,";
	szFeatures += "left=0,";
	szFeatures += "width=" + width + ",";
	szFeatures += "height=" + height + ",";
	szFeatures += "directories=no,";
	szFeatures += "status=yes,toolbar=no,location=no,";
	szFeatures += "menubar=no,";
	szFeatures += "scrollbars=yes,";
	szFeatures += "resizable=yes";
    }
    if(Sys.chrome) {
       
        obj.on("load",function(){
            let spaWin = window.open("/spa/crm/index.html#"+routeUrl, "_blank", szFeatures);
            if(!spaWin) message.warning("对不起，流程表单弹窗被chrome阻止，请点击浏览器地址栏尾部配置例外！",5);
            $(window).unbind("mousedown");
            obj.unbind("load");
        });
    }
    else {
        window.open("/spa/crm/index.html#"+routeUrl, "", szFeatures);
    }
}

class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

ContactQuery = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(ContactQuery);
//form 表单与 redux 双向绑定
ContactQuery = createForm({
    //当 Form.Item 子节点的值发生改变时触发，可以把对应的值转存到 Redux store
	onFieldsChange(props, fields) {
        props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.orderFields.toJS();
  	}
})(ContactQuery);

function mapStateToProps(state) {
	const {crmcontactQuery,comsWeaTable} = state;
    return  {
    	loading: crmcontactQuery.get('loading'),
        title: crmcontactQuery.get('title'),
        dataKey: crmcontactQuery.get('dataKey'),
        conditioninfo: crmcontactQuery.get('conditioninfo'),
        showSearchAd: crmcontactQuery.get('showSearchAd'),
        searchParamsAd: crmcontactQuery.get('searchParamsAd'),
        orderFields: crmcontactQuery.get('orderFields'),
        isClearNowPageStatus:crmcontactQuery.get("isClearNowPageStatus"),
        hasright:crmcontactQuery.get('hasright'),
		//table
        comsWeaTable: comsWeaTable, //绑定整个table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...ContactQueryAction,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ContactQuery);